/**********************************************************************/
/*
   Title: villages_podes.do
   Authors: Clotaire Boyer
   Created: 2020 11 24
   Description: Runs village level regs on PODES 2019
*/
/**********************************************************************/


cap log close
local prefix: display %tdCYND td(`c(current_date)')
log using "$log/`prefix'_vill_podes", replace text

clear
set more off

set seed 11022022

global finance_data "$cleaned/finance"

qui cd "$output/ster_files/20210226_finance"

u "$cleaned/podes_2019_oursample.dta", clear

/*  If needed depending on stata/pdslasso version:
encode KABU, gen(_KABU)
drop KABU
ren _KABU KABU
*/

local smallbuis_alltypes "typej_n typege_n typef_n"

* locals for regressions
local 0    = "agents_mar18 == 0"
local 2    = "agents_mar18 < 2 & agents_mar18 >= 0"
local full = "1==1"

gen KABU = Kode_Provinsi + Kode_Kabupaten

gen namakabupaten = Kabupaten

foreach var of varlist  `smallbuis_alltypes'  {

  * get baseline control if it exists
  local mar18 = ""
  cap confirm variable `var'_podes18
  if _rc == 0 {
    local mar18 = "`var'_podes18"
  }


    foreach sample in 0 full { //2

      di "Var: `var' Sample: `sample'"

      * DL regression


          eststo `var'`sample': pdslasso `var' treated (`mar18' *podes i.finalstratum) ///
          if ``sample'', cluster(KABU) aset(i.finalstratum `mar18')
          summ `var' if e(sample) == 1 & treated == 0
          estadd scalar control_mean = r(mean)
          estadd scalar obs = e(N)
          estadd local stratum = "Yes"
          estadd local lasso = "Yes"


      * RI p-val
      randinference treated using "$importable/resample1000.dta", ///
        reg(reg `var' treated `e(xselected)' if ``sample'', vce(cluster KABU)) ///
        reps($RI) mergevar(namakabupaten) mergetype(m:1)
      matrix define pvalues = (`r(RIpval)')
      matrix colnames pvalues = treated
      est restore `var'`sample'
      estadd matrix pvalues
    }
  }


local prefix: display %tdCYND td(`c(current_date)')
cap erase "$output/ster_files/20210226_finance/`prefix'_allbusinessespodes" // clear .ster if it already exists
qui estimates dir
foreach e in `r(names)' {
    quietly estimates restore `e'
    estimates title: `e'
    quietly estimates save "$output/ster_files/20210226_finance/`prefix'_allbusinessespodes", append
}

log close

// end
